<template>
  <div>
    <el-button type="primary" @click="addOpen = true">添加角色</el-button>
    <el-table :data="roleList" border stripe>
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-row
            :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
            v-for="(item1, i1) in scope.row.children"
            :key="item1.id"
          >
            <!-- 渲染一级权限 -->
            <el-col :span="5">
              <el-tag closable @close="delRightsId(scope.row.id, item1.id)">{{
                item1.authName
              }}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 渲染二级和三级权限 -->
            <el-col :span="19">
              <!-- 通过 for 循环 嵌套渲染二级权限 -->
              <el-row
                :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                v-for="(item2, i2) in item1.children"
                :key="item2.id"
              >
                <el-col :span="6">
                  <el-tag
                    type="success"
                    closable
                    @close="delRightsId(scope.row.id, item2.id)"
                    >{{ item2.authName }}</el-tag
                  >
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="18">
                  <el-tag
                    type="warning"
                    v-for="item3 in item2.children"
                    :key="item3.id"
                    closable
                    @close="delRightsId(scope.row.id, item3.id)"
                    >{{ item3.authName }}</el-tag
                  >
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column type="index" width="50"> </el-table-column>
      <el-table-column label="角色名称" prop="roleName"> </el-table-column>
      <el-table-column label="角色描述" prop="roleDesc"> </el-table-column>
      <el-table-column label="操作" prop="desc" width="300px">
        <template v-slot="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="editRights(scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="delRights(scope.row.id)"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="warning"
            icon="el-icon-setting"
            @click="showOpen(scope.row)"
            >分配权限</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 弹出权限列表 -->
    <el-dialog class="dialog" :visible.sync="isShow" title="分配权限">
      <el-tree
        ref="tree"
        :data="rightslist"
        show-checkbox
        node-key="id"
        :default-expanded-keys="defKeys"
        :default-checked-keys="defKeys"
        :props="treeProps"
      >
      </el-tree>
      <el-button @click="isShow = false">取 消</el-button>
      <el-button type="primary" @click="rights2">确 定</el-button>
    </el-dialog>

    <el-dialog class="dialog" :visible.sync="addOpen" :title="title">
      <el-form
        :model="form"
        :inline="true"
        label-position="right"
        ref="form"
        label-width="100px"
        class="form"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="form.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <el-button @click="isShow = false">取 消</el-button>
      <el-button type="primary" @click="addOk">确 定</el-button>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRoles,
  addrole,
  editrole,
  delrole,
  delroleById,
  allrights,
  updaterole,
} from "../utils/api";

export default {
  props: {},
  data() {
    return {
      roleList: [],
      title: "添加",
      isShow: false,
      defKeys: [],
      form: {
        roleName: "",
        roleDesc: "",
      },
      editId: "",
      roleId: "",
      addOpen: false,
      treeProps: {
        label: "authName",
        children: "children",
      },
      rightId: "",
      // 权限数据
      rightslist: [
        {
          id: 101,
          authName: "商品管理",
          path: "goods",
          pid: 0,
          children: [
            {
              id: 104,
              authName: "商品列表",
              path: "goods",
              pid: 101,
              children: [
                {
                  id: 105,
                  authName: "添加商品",
                  path: "goods",
                  pid: "104,101",
                },
              ],
            },
          ],
        },
      ],
    };
  },
  computed: {},
  created() {
    this.render();
  },
  mounted() {},
  watch: {},
  methods: {
    // 渲染
    render() {
      getRoles().then((res) => {
        console.log(res);
        if (res.meta.status === 200) {
          this.$message.success(res.meta.msg);
          this.roleList = res.data;
        }
      });
    },
    // 编辑角色
    editRights(row) {
      this.addOpen = true;
      this.title = "编辑";
      console.log(row);
      this.form.roleName = row.roleName;
      this.form.roleDesc = row.roleDesc;
      this.editId = row.id;
    },
    // 添加角色
    addOk() {
      if (this.editId) {
        editrole({
          id: this.editId,
          roleName: this.form.roleName,
          roleDesc: this.form.roleDesc,
        }).then((res) => {
          console.log(res);
          this.addOpen = false;
          this.render();
        });
      } else {
        addrole({
          roleName: this.form.roleName,
          roleDesc: this.form.roleDesc,
        }).then((res) => {
          console.log(res);
          this.render();
          this.form = {};
          this.addOpen = false;
        });
      }
    },
    // 权限弹出
    showOpen(role) {
      console.log("角色信息", role);
      this.roleId = role.id;
      this.isShow = true;
      this.defKeys = [];
      allrights("tree").then((res) => {
        console.log("所有权限", res);
        if (res.meta.status === 200) {
          this.$message.success(res.meta.msg);
          this.rightslist = res.data;
          console.log("当前角色下所有权限", role);
          let arr = [];
          function fn(role) {
            if (!role.children) {
              return arr.push(role.id);
            }
            role.children.forEach((item) => fn(item));
          }
          fn(role);
          console.log("默认选择权限", arr);
          this.defKeys = arr;
        }
      });
    },
    // 删除当前行权限

    delRightsId(roleId, rightId) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delroleById({ roleId: roleId, rightId: rightId }).then((res) => {
            console.log(res);
            this.render();
          });
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 删除整行权限
    delRights(id) {
      console.log("删除");
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delrole(id).then((res) => {
            console.log(res);
            this.render();
          });
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 权限选择确定
    rights2() {
      console.log(this.$refs.tree, 111111111);
      let allCheck = this.$refs.tree.getCheckedKeys(); //这是打对勾的选中，
      let halfCheck = this.$refs.tree.getHalfCheckedKeys(); //这是半选中
      console.log("全选中的", allCheck, halfCheck);
      //合并数据
      let arrAll = [...allCheck, ...halfCheck];
      let idStr = arrAll.join(",");
      updaterole({ id: this.roleId, rids: idStr }).then((res) => {
        if (res.meta.status === 200) {
          this.$message.success(res.meta.msg);

          this.isShow = false;
        }
        this.render();
      });
    },
  },
  components: {},
};
</script>

<style scoped lang="scss">
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
.el-button--mini {
  padding: 7px 12px;
}
</style>
